package com.xiechuang.helper;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Description: 请求助手
 * @Author: xiechuang
 * @Date: 2023/1/11
 */
public class RequestHelper {

    private final static ThreadLocal<RequestHelper> local = new ThreadLocal();
    private HttpServletRequest request;
    private HttpServletResponse response;
    private ServletContext servletContext;
    private long enterTimer;

    public static void set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        RequestHelper requestHelper = new RequestHelper();
        requestHelper.request = request;
        requestHelper.response = response;
        requestHelper.servletContext = servletContext;
        requestHelper.enterTimer = System.currentTimeMillis();
        local.set(requestHelper);
    }

    public static void set(HttpServletRequest request, HttpServletResponse response) {
        RequestHelper requestHelper = new RequestHelper();
        requestHelper.request = request;
        requestHelper.response = response;
        requestHelper.enterTimer = System.currentTimeMillis();
        local.set(requestHelper);
    }

    public static HttpServletRequest getRequest() {
        RequestHelper requestHelper = local.get();
        return null == requestHelper ? null : requestHelper.request;
    }

    public static ServletContext getServletContext() {
        RequestHelper requestHelper = local.get();
        return null == requestHelper ? null : requestHelper.servletContext;
    }

    public static HttpServletResponse getResponse() {
        RequestHelper requestHelper = local.get();
        return null == requestHelper ? null : requestHelper.response;
    }

    public static long getEnterTimer() {
        RequestHelper requestHelper = local.get();
        return null == requestHelper ? null : requestHelper.enterTimer;
    }

    public static void clean() {
        local.set(null);
    }

    public static <T> T getAttr(String key) {
        return (T) Objects.requireNonNull(getRequest()).getAttribute(key);
    }

    public static void setAttr(String key, Object value) {
        Objects.requireNonNull(getRequest()).setAttribute(key, value);
    }

}
